#!/bin/bash

inform() {
	echo ""
	echo "submodule vender is not existed!"
	echo "you can execute the given command to init and update it."
	echo " \$ git submodule init"
	echo " \$ git submodule update"
	echo ""
	exit 1
}

TIME_BEGIN=$(date +%s)

. ./vender/build_tools/scripts/build_env.sh

dev=0
build_addon=0

new_args=()
for arg in "$@"; do
	if [ "$arg" == "dev" ]; then
		dev=1
		build_addon=1
	elif [ "$arg" == "ci" ]; then
		export USE_VENDER_DIST=1
		build_addon=1
	else
		new_args+=("$arg")
	fi
done
set -- "${new_args[@]}"

if [ $dev == 0 ] && [ -z $USE_VENDER_DIST ]; then
	export USE_VENDER_DIST=1
	git submodule update --init --recursive
elif [ ! -z $VENDER_TAG ]; then
	export USE_VENDER_DIST=1
fi

if [ -f "${WORK_ROOT}/vender/build" ]; then
	if [ "$USE_VENDER_DIST" != "1" ]; then
		cd "${WORK_ROOT}/vender"
		bash build "$@"
		if [ $? != 0 ]; then
			exit 1
		fi
	fi
else
	inform
fi

cd "${WORK_ROOT}/fibjs"
bash build "$@"
if [ $? != 0 ]; then
	exit 1
fi

cd "${WORK_ROOT}/fibjs/program"
bash build "$@"
if [ $? != 0 ]; then
	exit 1
fi

if [ $build_addon == 1 ]; then
	cd "${WORK_ROOT}/fibjs/addons"
	bash build "$@"
	if [ $? != 0 ]; then
		exit 1
	fi
fi

cd "${WORK_ROOT}/fibjs/installer"
bash build "$@"
if [ $? != 0 ]; then
	exit 1
fi

bldred="\033[1m\033[31m"
txtrst="\033[0m"
TIME_END=$(($(date -u +%s) - $TIME_BEGIN))

printf "\n\n"
printf "\t${bldred} _______ _________ ______  _________ _______ ${txtrst}\n"
printf "\t${bldred}(  ____ \\\\\\__   __/(  ___ \\ \\__    _/(  ____ \\\\${txtrst}\n"
printf "\t${bldred}| (    \\/   ) (   | (   ) )   )  (  | (    \\/${txtrst}\n"
printf "\t${bldred}| (__       | |   | (__/ /    |  |  | (_____ ${txtrst}\n"
printf "\t${bldred}|  __)      | |   |  __ (     |  |  (_____  )${txtrst}\n"
printf "\t${bldred}| (         | |   | (  \\ \\    |  |        ) |${txtrst}\n"
printf "\t${bldred}| (_     ___) (___| (___) )/\\_)  )  /\\____) |${txtrst}\n"
printf "\t${bldred}(__/     \\_______/(______/ \\____/   \\_______)${txtrst}\n"
printf ""

printf "\\n\\tFIBJS has been successfully built during  $(($TIME_END / 3600)):$(($TIME_END % 3600 / 60)):$(($TIME_END % 60))\\n\\n"

printf "\\tFor more information:\\n\\n"
printf "\\twebsite: https://fibjs.org\\n"
printf "\\trepository: https://github.com/fibjs\\n"
printf "\n\n"
